package com.lagou.web.filter;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.*;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@Component
@WebFilter(filterName = "transPortIPFilter", urlPatterns = "/*")
@Activate(group = Constants.CONSUMER)
public class TransPortIPFilter implements Filter,javax.servlet.Filter {

    private static ThreadLocal<ServletRequest> REQUEST_THEAD_LOCAL = new ThreadLocal<>();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try{
            REQUEST_THEAD_LOCAL.set(servletRequest);
            filterChain.doFilter(servletRequest,servletResponse);
        } finally {
            REQUEST_THEAD_LOCAL.remove();
        }
    }


    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        RpcContext.getContext().setAttachment("requestIP", REQUEST_THEAD_LOCAL.get().getRemoteAddr());

        return invoker.invoke(invocation);
    }


}
